
import { createContext, useContext } from 'react';
import { isArray, isFunction, isObservable } from '@legendapp/state';
import { useSelector } from '@legendapp/state/react';
import {
    blue,
    cyan,
    geekblue,
    gold,
    green,
    grey,
    lime,
    magenta,
    purple,
    red,
    volcano,
    yellow,
} from '@ant-design/colors';

const Context = createContext({});

export function getObservableValue(currState: unknown) {
    if (isObservable(currState)) {
        // eslint-disable-next-line react-hooks/rules-of-hooks
        const res = useSelector(currState, {});
        if (res?.get) {
            return res?.get?.();
        }
        return res;
    }

    console.error('get observable value error!');
    return null;
}

/**
 * 判断当前传入的如果是Observable对象，返回Selector后的数据，否则返回原始值
 * @param currState
 * @returns
 */
export function handleObservable(currState: unknown) {
    if (isObservable(currState)) {
        return getObservableValue(currState);
    }
    return currState;
}

/**
 * 获取SelectData
 * @param currState
 * @returns
 */
export function getSelectorData(currState: unknown) {
    // console.log('q=>getState', currState);
    if (isObservable(currState)) {
        return getObservableValue(currState);
    }
    if (isFunction(currState)) {
        return currState;
    }
    if (isArray(currState)) {
        return currState.map((curr) => {
            return handleObservable(curr);
        });
    }
    // if (isObject(currState)) {
    //   const newObject: Record<string, unknown> = {};
    //   Object.keys(currState).forEach(key => {
    //     newObject[key] = handleObservable(currState[key]);
    //   })
    //   return newObject;
    // }
}
/**
 * selector选择器
 * @param selector
 * @returns
 */
export function useFormContainerSelector<R extends any>(
    selector: (s: any) => R
) {
    const tableState = useContext(Context);
    let currState = selector(tableState);

    currState = getSelectorData(currState);
    return currState;
}







export const baseColorMap = {
    blue,
    red,
    volcano,
    gold,
    yellow,
    geekblue,
    lime,
    green,
    cyan,
    purple,
    magenta,
    grey,
};
/**
 * 判断是否是自定义颜色
 * @param color
 */
export const isCustomerColor = (color: string) => {
    return color?.startsWith?.('#');
};

/**
 * 获取具体的颜色值
 * @param color
 */
export const getColor = (color: string) => {
    if (isCustomerColor(color)) return color;
    const [prefix, number] = color?.split?.('-');

    return baseColorMap?.[prefix as unknown as keyof typeof baseColorMap]?.[
        number as unknown as number
    ];
};